<?php
namespace app\admin\server\index;
use think\Request;
use app\admin\server\index\login as loginServer;
use app\admin\ServerBase;
use think\exception\ValidateException;
use think\config;
use app\admin\model\index\Admin as AdminModel;
use app\admin\server\menu\Menu as MenuServer;
use app\admin\common;
use app\admin\server\system\Department as departmentServer;

class Admin extends ServerBase{
	public static $s_model;
    public function __construct(Request $request)
    {
    	$this->checkAuth();
        $this->REQUEST = $request;
        self::$s_model=new AdminModel();
    }
    
    public $weekarray=array(1=>"一",2=>"二",3=>"三",4=>"四",5=>"五",6=>"六",7=>"日");
    public function index(){
    	$operation=$this->getOperationUser()['or_data'];
    	$id=$operation['id'];
    	$last_data=common::getlog(['function'=>'LoginMobile','admin_id'=>$id,'type'=>0],1,'*',"id desc");
    	$_data=[
	    		'username'=>$operation['username'],
	    		'last_date'=>'',
	    		'wekk'=>'',
	    		'last_hours'=>'',
	   	];
    	if(!empty($last_data)){
	    	$_data['last_date']=date('Y-m-d',$last_data['create_time']);
	    	$_data['wekk']='星期'.$this->weekarray[date('N',$last_data['create_time'])];
	    	$_data['last_hours']=date('H:i:s',$last_data['create_time']);
    	}
    	$this->getMessageCode('adminMessage.success.select',2);
    	return $_data;
    }
    
    
    public function selectMenu(){
    	$menu_obj=new MenuServer($this->REQUEST);
		//1.获取用户左边的菜单列表
		$menu=$menu_obj->getUserLeftMenu();
		$this->getMessageCode('adminMessage.success.select',2);
		return $menu;
    }
    
    //处理管理员权限问题  默认设置roles_id 1为平台管理员  可以管理所有， 其他的则用pid来关联
    public function check_admin_role(&$where){
    	$common=new common();
    	$perssion_role=$operation=$common->checkRole();
    	
    	if($perssion_role==0){
    		//获取操作用户的自己Id 
    		$operation=$common->getOperation();
    		$where[]=array(
    			"pid|id","=",$operation['id']
    		);
    	}
    }
    
    /**
     * 查询管理员数据
     */
    public function select(){
    	//$data=$this->REQUEST->param();
    	$data=$this->checkParam($this->REQUEST->param());
    	$limit=$this->getPage($data);//获取整理好后的分布
    	$order=['last_update_time'=>'desc'];
    	$where[]=["is_del","<>",2];
    	if(isset($data['id']) && !empty($data['id'])){
    		$where[]=array(
    			"id","=",$data['id']
    		);
    	}
    	if(isset($data['admin_id']) && !empty($data['admin_id'])){
    		$where[]=array(
    			"id","=",$data['admin_id']
    		);
    	}
    	if(isset($data['search_name']) && !empty($data['search_name'])){
    		$where[]=array(
    			'username|account',"like",'%'.$data['search_name']."%"
    		);
    	}
    	//处理用户权限
    	$this->check_admin_role($where);
		$count=self::$s_model->selectAdminDataCount($where);
		$data=self::$s_model->selectAdminData($where,$order,$limit);
		$_department_obj=new departmentServer($this->REQUEST);
		$_department_ids=array_unique(array_column($data,'department_id'));
		$this->REQUEST->setRoute(['is_check'=>1,'id'=>$_department_ids]);
		$_department_data=$_department_obj->selectDepartmentName();
		foreach($data as $k=>$v){
			$data[$k]['last_update_time']=date('Y-m-d H:i',$v['last_update_time']);
			$data[$k]['department_name']=isset($_department_data[$v['department_id']])?$_department_data[$v['department_id']]['name']:'';
		}
		$result['data']=$data;
		$result['count']=$this->getPageCount($count['num']);
    	$this->getMessageCode('adminMessage.success.select',2);
    	return $result;
    }
    
    /**
     * @Purpose 查找单个数据的详情
     */
    public function findAdmin()
    {
    	$_param=$this->REQUEST->param();
    	$_where=[
    		"id"=>$_param['id']
    	];
    	$_field="*";
    	$_details=self::$s_model->findAdminData($_where,$_field);
    	if(!$_details){
    		$this->getMessageCode('adminMessage.error.select',1);
    		return false;
    	}
    	$this->getMessageCode('adminMessage.success.select',2);
    	return $_details;
    }
    
    /**
     * @Purpose 更新当前员工的状态
     */
    public function updateAdminStatus(){
    	$_param=$this->REQUEST->param();
    	$_id=$_param['id'];
    	$_status=$_param['status'];
    	$_operation=$this->getOperationUser();
    	if($_param['id']==1){
			$this->getMessageCode('adminMessage.error.is_admin',1);
			return false;
		}
    	$_up=[
    		"last_update_admin"=>$_operation['update_admin'],
    		'last_update_time'=>time(),
    		'status'=>$_status,
    	];
    	$_where=["id"=>$_id];
    	if(!self::$s_model->getAdmin($_where,"*")){
    		$this->getMessageCode('adminMessage.id.error',1);
    		return false;
    	}
    	$_up_flag=self::$s_model->updateAdmin($_up,$_where);
    	return $this->return_server($_up_flag,'update');
    }
 
	/**
	 * @Purpose 添加管理员帐号
	 */
	public function addAdmin(){
		$_data=$this->REQUEST->param();
        //1.验证当前手机号是否唯一
        $_insert_account=self::$s_model->getAdmin(['mobile'=>$_data['mobile']]);
        if(!empty($_insert_account)){
        	$this->getMessageCode('adminMessage.mobile.isBind',1);
        	return false;
        }
        $_data_insert=$this->getInsertData($_data);
		$id=self::$s_model->insertAdminData($_data_insert);
		return $this->return_server($id,'insert');
	}
	
	public function getInsertData($_data){
		 $_operation=$this->getOperationUser();
		$_data_insert=[
        	'username'=>$_data['username'],
        	'mobile'=>$_data['mobile'],
        	'department_id'=>$_data['department_id'],
        //	'job_id'=>$_data['job_id'],
        	'remark'=>isset($_data['remark'])?$_data['remark']:'',
        	'status'=>$_data['status'],
        	'sex'=>$_data['sex'],
        	'create_time'=>time(),
        	'passwd'=>common::token(config('key.passwd'),config('key.pass_salt')),
        	'roles_id'=>0,
        	'last_update_time'=>time(),
        	'last_update_admin'=>$_operation['update_admin']
        ];
        return $_data_insert;
	}
	
	/**
	 * @Purpose 更新数据
	 */
	public function editAdmin(){
		$data=$this->REQUEST->param();
        //2.检测当前手机号是否唯一
        $_where[]=['mobile',"=",$data['mobile']];
        $_where[]=["id","<>",$data['id']];
        $_insert_account=self::$s_model->getAdmin($_where);
        if(!empty($_insert_account)){
        	$this->getMessageCode('adminMessage.mobile.isBind',1);
        	return false;
        }
       	$data_up=$this->getUpdateData($data);
		$id=self::$s_model->updateAdmin($data_up,['id'=>$data['id']]);
		return $this->return_server($id,'update');
	}
	
	public function getUpdateData($_data)
	{
		$_operation=$this->getOperationUser();
		$_insert_data=[
        	'username'=>$_data['username'],
        	'department_id'=>isset($_data['department_id'])?$_data['department_id']:0,
        	'status'=>$_data['status'],
        	'sex'=>$_data['sex'],
       // 	'job_id'=>$_data['job_id'],
        	'remark'=>isset($_data['remark'])?$_data['remark']:'',
        	'last_update_time'=>time(),
        	'last_update_admin'=>$_operation['update_admin']
        ];
		return $_insert_data;
	}
	
	/**
	 * @Purpose 删除数据
	 */
	public function deleteAdmin()
	{
		$_param=$this->REQUEST->param();
		$_details=$this->findAdmin();
		if($_details['is_del']==2){
			$this->getMessageCode('adminMessage.error.is_delete',1);
			return false;
		}
		if($_param['id']==1){
			$this->getMessageCode('adminMessage.error.is_admin',1);
			return false;
		}
		$_operation=$this->getOperationUser();
		$_up=[
    		"last_update_admin"=>$_operation['update_admin'],
    		'last_update_time'=>time(),
    		'is_del'=>2,
    	];
    	$_where=["id"=>$_param['id']];
    	$_up_flag=self::$s_model->updateAdmin($_up,$_where);
    	return $this->return_server($_up_flag,'delete');
	}
	
	/**
	 * @Purpose 重置密码
	 */
	public function resetPasswd(){
		$_ids=$this->REQUEST->param();
		$_operation=$this->getOperationUser();
		//var_dump($_ids);exit;
		$_up=[
    		"last_update_admin"=>$_operation['update_admin'],
    		'last_update_time'=>time(),
    		'passwd'=>common::token(config('key.passwd'),config('key.pass_salt')),
    	];
    	
		$_update_data=self::$s_model->updateAdmin($_up,['id',"IN",$_ids['ids']]);
		
		return $this->return_server($_update_data,'reset');
	}
	
	/**
	 * @Purpose 设置密码
	 */
	public function setPasswd(){
		$_param=$this->REQUEST->param();
		$_operation=$this->getOperationUser();
		$_where=["id"=>$_operation['or_data']['id']];
		$_field="*";
		$_details=self::$s_model->findAdminData($_where,$_field);
		if(!$_details){
			$this->getMessageCode('adminMessage.error.not_exis',1);
			return false;
		}
		if($_details['is_del']==2){
			$this->getMessageCode('adminMessage.error.is_delete',1);
			return false;
		}
		if(common::token($_param['oldPasswd'],config('key.pass_salt'))!=$_details['passwd'])
		{
			$this->getMessageCode('adminMessage.login.setPasswd',1);
			return false;
		}
		$_up=[
    		"last_update_admin"=>$_operation['update_admin'],
    		'last_update_time'=>time(),
    		'passwd'=>common::token($_param['newPasswd'],config('key.pass_salt')),
    	];
		$_update_data=self::$s_model->updateAdmin($_up,$_where);
		return $this->return_server($_update_data,'updatePasswd');
	}

}
?>